# -*- coding: utf-8 -*-

'''eof
name:企业近2年内法定代表人变更次数校验
code:R08_EG_CorporationChangeCntTwentyfourMonsCheck
tableName:
columnName:
groups:企业业务信息校验
dependencies:EG_DSJ
type:常用指标
datasourceType:在线指标
description:
eof'''

import sys
import pandas as pd
import json
from datetime import datetime


def FormatData(tableName):
    try:
        eg = EG_DSJ.get("data").get("R1103V3")[0].get(tableName)
        return eg if isinstance(eg, list) else [{}]
    except:
        return [{}]


def get_date_list(month):
    try:
        now = datetime.now()
        aaa = [(now - pd.tseries.offsets.DateOffset(months=i)).strftime('%Y%m%d') for i in [month, 0]]
        return aaa
    except:
        return None


# 统一转成datetime对象，只能转年月日的字符串
def date_format(time):
    import re
    r = re.compile(r'\D+')
    try:
        date = datetime.strptime(time, '%Y.%m.%d').strftime('%Y%m%d')
    except:
        try:
            date = datetime.strptime(time, '%Y-%m-%d').strftime('%Y%m%d')
        except:
            try:
                date = datetime.strptime(time, '%Y/%m/%d').strftime('%Y%m%d')
            except:
                try:
                    tmp = r.sub('', time)
                    date = datetime.strptime(tmp, '%Y%m%d').strftime('%Y%m%d')
                except:
                    date = None
    return date


def getRule08():
    null_type_list = ['', ' ', None, 'null', 'Null', 'NULL', '/', '-', '--']
    itemList = [u'法人代表变更', u'负责人变更（法定代表人、负责人、首席代表、个体户经营者、投资人、合伙事务执行人等变更）',
                u'法定代表人（负责人）变更', u'执行合伙企业事务的合伙人', u'法定代表人变更', u'法定代表人姓名',
                u'负责人（法定代表人、首席代表、合伙事务执行人等）变更', u'法定代表人（负责人、董事长、首席代表）变更',
                u'负责人变更（法定代表人、负责人、首席代表、合伙事务执行人等变更）', u'法定代表人（负责人、董事长、首席代表）变更',
                u'法定代表人', u'执行合伙企业事务的合伙', u'法定代表人（负责人、独资投资人）',
                u'负责人变更（法定代表人、负责人、首席代表、合伙事务执行人等变更）变更', u'负责人变更', u'法定代表人（负责人）',
                u'经营者姓名', u'负责人变更（法定代表人、负责人、首席代表、个体户经营者、投资人、合伙事务执行人等变更）']
    basic_list = FormatData("alterList")
    lastRejectionTime = date_format(ratingRequest.get("LastRejectionTime"))
    if basic_list == [{}]:
        return u'缺失值'
    else:
        if len(basic_list) >= 1:
            resultList = []
            resultList1 = []
            flag = False
            date_list = get_date_list(24)
            date_list1 = get_date_list(12)
            for i in basic_list:
                altDate = i.get("altDate")
                altItem = i.get("altItem")
                if altDate not in null_type_list and altItem not in null_type_list and date_format(altDate[0:10]) not in null_type_list:
                    altDate = date_format(altDate[0:10])
                    altItem = altItem.replace("(", u"（")
                    altItem = altItem.replace(")", u"）")
                    flag = True
                    if altItem in itemList and date_list[0] < date_format(altDate[0:10]) <= date_list[1]:
                        resultList.append(1)
                    if altItem in itemList and date_list1[0] < date_format(altDate[0:10]) <= date_list1[1]:
                        resultList1.append(1)
            if lastRejectionTime not in null_type_list and date_list1[0] < lastRejectionTime <= date_list1[1] and sum(resultList1) > 0:
                return 9999
            return sum(resultList) if flag else u'缺失值'
        else:
            return 0


if __name__ == "__main__":
    file_obj = open(r'../data/rating/R08_EG_CorporationChangeCntTwentyfourMonsCheck/EG_DSJ.json', 'r')
    content = file_obj.read()
    EG_DSJ = json.loads(content, strict=False)
    aa = getRule08()
    print aa

result = getRule08()
